package cn.tuling.interceptors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 记录请求开始时间 & 完成处理消耗时间
 */
public class TimeInterceptor implements HandlerInterceptor {

    LocalDateTime begin;
    Logger log = LoggerFactory.getLogger(TimeInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        begin = LocalDateTime.now();
        log.info("处理请求 {}, 开始时间 {}", request.getRequestURI(), begin);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LocalDateTime end = LocalDateTime.now();

        Duration between = Duration.between(begin, end);
        long seconds = between.toMillis();

        log.info("处理请求 {}, 消耗时间 {} 毫秒", request.getRequestURI(), seconds);
    }
}
